var express = require('express');
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
var router = express.Router();
var { UserModel, GongModel, TypeModel, ContentModel, SearchModel, FeiModel, PeopleModel, } = require('../model/model')
const SMSClient = require('@alicloud/sms-sdk');
const jwt = require('jsonwebtoken')

var {
    TypeModel,
    ContentModel,
    order_CateModel,
    order_ListModel,
    addressCateModel,
    addressModel,
    guanZhuModel,
    guanZhuCateModel,
    guanDongCateModel,
    guanDongModel,
    yuYueCateModel,
    yuYueModel,
    caiCateModel,
    caiListModel,
    shopModel,
    commodityModel,
    ShequModel,
    HuatiModel,
    TieziModel,
    pinglunContentModel,
    concernShopModel,
    ShoppingCartModel,
    eventModel,
}=require('../model/model')
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


const { createServer } = require("node:http");
const { join } = require("node:path");
const app = express();
const server = createServer(app);
const { Server } = require("socket.io"); //socket.io
var router = express.Router();
const cors = require('cors');
const path = require('path')
app.use(cors());
app.use('/uploads', express.static(path.join(__dirname, '/uploads')));
app.use('/audioUploads', express.static(path.join(__dirname, 'audioUploads')));
// 引入 fs 模块
const fs = require('fs')
const multer = require('multer');

// 引入 Server 类，用于创建 socket.io 服务器
const io = new Server(server, { cors: true }, { connectionStateRecovery: {} });

// 定义根路径的 GET 请求处理函数，当访问根路径时，发送 index.html 文件给客户端
app.get("/", (req, res) => {
  // 使用 join 函数将当前目录和 index.html 文件路径拼接起来
  // 并将该文件发送给客户端
  res.sendFile(join(__dirname, "index.html"));
});

// 配置 multer 的磁盘存储策略，用于处理图片上传
const storage = multer.diskStorage({
  // 设置文件存储的目标目录
  destination: (req, file, cb) => {
    // 拼接上传目录的路径
    const uploadDir = join(__dirname, 'uploads');
    // 检查上传目录是否存在
    if (!fs.existsSync(uploadDir)) {
      // 如果不存在，则创建该目录，使用递归选项确保可以创建多级目录
      fs.mkdir(uploadDir, { recursive: true }, (err) => {
        // 如果创建过程中出现错误，将错误传递给回调函数
        if (err) {
          return cb(err);
        }
        // 若创建成功，将上传目录路径传递给回调函数
        cb(null, uploadDir);
      });
    } else {
      // 若目录已存在，直接将上传目录路径传递给回调函数
      cb(null, uploadDir);
    }
  },
  // 设置上传文件的文件名
  filename: (req, file, cb) => {
    // 将文件名从 latin1 编码转换为 utf-8 编码
    const buf = Buffer.from(file.originalname, 'latin1');
    const fileName = buf.toString('utf-8');
    // 将当前时间戳和文件名拼接起来，避免文件名冲突
    cb(null, Date.now() + '-' + fileName);
  },
});



// 使用配置好的存储策略创建 multer 实例，用于处理图片上传
const upload = multer({ storage });

// 定义 /upload 路径的 POST 请求处理函数，用于处理图片上传
router.post('/upload', upload.single('image'), (req, res) => {
  // 获取上传图片文件的路径
  const imagePath = req.file.path;
  // 从请求体中获取发送者的用户名
  const sender = req.body.username;
  // 通过 socket.io 向所有连接的客户端发送图片消息
  io.emit('imageMessage', { path: imagePath, isUploaded: true, username: sender });
  // 向客户端发送响应，告知图片上传成功
  res.send('图片上传成功');
});

// 监听 socket.io 的连接事件，当有新的客户端连接时触发
io.on('connection', (socket) => {
  // 监听客户端发送的 message 事件
  socket.on('message', (dispatcher, user) => {
    // 打印接收到的消息和发送者信息
    // console.log(dispatcher, user);
    // 通过 socket.io 向所有连接的客户端广播该消息
    io.emit('message', dispatcher, user);
  });

  // 监听客户端发送的 imageMessage 事件
  socket.on('imageMessage', async (imageData, user) => {
    // 去除图片数据的前缀，只保留 base64 编码部分
    const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '');
    // 将 base64 编码的数据转换为二进制缓冲区
    const buffer = Buffer.from(base64Data, 'base64');
    // 拼接图片上传目录的路径
    const uploadDir = join(__dirname, 'uploads');
    try {
      // 检查上传目录是否存在
      await fs.access(uploadDir);
    } catch (error) {
      // 如果目录不存在，则创建该目录，使用递归选项确保可以创建多级目录
      await fs.mkdir(uploadDir, { recursive: true });
    }
    // 从图片数据中提取文件名
    const imageName = Date.now() + '-' + encodeURIComponent(imageData.match(/filename="([^"]+)"/)[1]);
    // 拼接图片文件的完整路径
    const imagePath = join(uploadDir, imageName);
    try {
      // 将二进制缓冲区的数据写入到指定的图片文件中
      await fs.writeFile(imagePath, buffer);
      // 通过 socket.io 向所有连接的客户端广播图片消息
      io.emit('imageMessage', { path: imagePath, isUploaded: false });
    } catch (error) {
      // 如果保存图片时出现错误，打印错误信息
      console.error('保存图片时出现错误：', error);
    }
  });

  // 监听客户端发送的 videoMessage 事件
  socket.on('videoMessage', async (video, user) => {
    // 打印接收到的视频信息和发送者信息
    console.log(video, user);
    // 通过 socket.io 向所有连接的客户端广播该视频消息
    io.emit('videoMessage', video, user);
  });
});

// 启动服务器，监听 3001 端口，当服务器启动成功后打印提示信息
server.listen(3001, () => {
  console.log("server running at http://localhost:3001");
});



//刷新token
router.get('/refresh', async (req, res) => {
  let token = req.query.token
  let name = ''
  try {
    let userInfo = jwt.verify(token, 'abckdefg')
    name = userInfo.name
  } catch (error) {
    console.log('错误');
    res.send({
      code: 414,
      msg: 'token失效，清重新登录'
    })
  }
  let userInfo = {
    name
  }
  let accessToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '5h' })
  let refreshToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '7d' })
  console.log('成功');
  res.send({
    accessToken,
    refreshToken,
  })
})






//手机号密码登录
router.post('/login2', async (req, res) => {
  let { phone, pass } = req.body
  let user = await UserModel.find()
  console.log(user);
  user.forEach(item => {
    if (item.phone != phone) {
      return res.send({ code: 400, msg: '用户不存在' })
    }
    if (item.pass != pass) {
      return res.send({ code: 400, msg: '密码错误' })
    }
  })
  const userInfo = { phone }
  const accessToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '3s' })
  const refreshToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '1d' })
  res.send({ code: 200, msg: '登陆成功', userInfo, accessToken, refreshToken })
})

// 注销
router.post('/delLogin', async (req, res) => {
  await UserModel.deleteMany()
  res.send({ cdoe: 200, msg: '删除成功' })
})

//忘记密码
router.post('/wang', async (req, res) => {
  let { phone, yan, pass } = req.body
  if (yan != msm) {
    return res.send({ code: 400, msg: '验证码错误' })
  }
  let user = await UserModel.findOne({ phone: phone })
  if (!user) {
    return res.send({ code: 400, msg: '用户不存在' })
  }
  let result = await UserModel.updateOne({ phone: phone }, { $set: { pass: pass } })
  if (!result.nModified) {
    return res.send({ code: 200, msg: '修改成功' })
  } else {
    return res.send({ code: 400, msg: '修改失败' })
  }
})

//人脸识别登录
router.post('/faceLogin', async (req, res) => {
  let b64 = req.body.b64
  const IaiClient = tencentcloud.iai.v20200303.Client;
  try {
    const clientConfig = {
      credential: {
        // 密钥
        secretId: "AKIDb2Wt78yb5NTM2Xpw8PflpkU4eGZhcPBn",
        secretKey: "SjofU5UgeQyKTO6aqulQuBF5i7PWYWaa"
      },


      region: 'ap-beijing',
      profile: { httpProfile: { endpoint: 'iai.tencentcloudapi.com' } }
    };
    const client = new IaiClient(clientConfig)
    const params = {
      // 人员库的ID
      "GroupIds": ["dxh0427dxh"],
      "Image": b64,
      "NeedPersonInfo": 1,
      "QualityControl": 0,
      "FaceMatchThreshold": 85,
    };
    let doc = await client.SearchFaces(params)
    if (doc.Results[0].Candidates.length != 0) {
      let token = jwt.sign({ name: doc.Results[0].Candidates[0].PersonName }, 'secret', { expiresIn: '1h' })
      let personName = doc.Results[0].Candidates[0].PersonName
      res.send({ code: 200, msg: '登录成功！', token })
      let user = await UserModel.findOne({ facename: personName })
      if (user.length != 0) {
        const accessToken = jwt.sign({ name: personName }, 'abcdefg', { expiresIn: '3s' })
        const refreshToken = jwt.sign({ name: personName }, 'abcdefg', { expiresIn: '1d' })
        res.send({ code: 200, msg: '登录成功！', accessToken, refreshToken, _id: user[0]._id })
      }
    } else {
      res.send({ code: 401, msg: '人脸库无此人！' })
      return false
    }
  } catch (err) {
    console.log(err)
  }
})

// 非遗工坊获取数据
router.get('/getHeritage', async (req, res) => {
  let data = await GongModel.find()
  res.send({
    code: 200,
    msg: "获取成功",
    data
  })
})




// 产生6位随机数（收到的验证码）
function getCode() {
  let str = "";
  for (let i = 0; i < 6; i++) {
    str += parseInt(Math.random() * 10)
  }
  return str;
}
// 发送短信验证码
router.post('/get_sms', function (req, res, next) {
  let phoneNum = req.body.phone;  //获取前端参数phone
  console.log(phoneNum);

  //初始化sms_client
  let smsClient = new SMSClient({
    accessKeyId: 'LTAI5tNyV4AgwZVctwqgA5mS',  //自己阿里云的accessKeyId
    secretAccessKey: 'Gkn7v3b70lxOn5fRykvgwvIX2jjtjH'  //自己阿里云的secretAccessKey
  });

  // 获取6位随机数
  let str = getCode();
  msm = str
  // 开始发送短信
  smsClient.sendSMS({
    PhoneNumbers: phoneNum,
    SignName: "yun2230", //签名名称,阿里云注册
    TemplateCode: "SMS_305050476", //模版CODE,阿里云注册 
    TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
  }).then(r => {
    console.log('执行成功');

    let { Code } = r;
    if (Code == 'OK') {
      res.send({
        code: 200,
        msg: 'success',
        sms: str
      })

    }
  })
    .catch(err => {
      res.send({
        code: 400,
        err
      })
    })
});


//手机号验证码登录
router.post('/login', async (req, res) => {
  try {
    let phone = req.body.phone
    let yan = req.query.yan
    console.log(phone, yan);
    const user = await UserModel.findOne({ phone })
    console.log(user);
    if (yan === msm) {
      const userInfo = { phone }
      const accessToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '3s' })
      const refreshToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '1d' })
      return res.send({ code: 200, msg: '登陆成功', accessToken, refreshToken })
    }
    if (!user) {
      await UserModel.create(req.body)
      return res.send({ code: 200, msg: '添加成功' })
    }
    res.send({ code: 400, msg: '登陆失败' })
  } catch (err) {
    res.status(500).send({ code: 500, msg: '服务器错误' })
  }
})

// 获取分类
router.get('/getType', async (req, res) => {
  const type = await TypeModel.find()
  res.send({ code: 200, msg: '获取成功', type })
})

// 获取内容
router.get('/getContent', async (req, res) => {
  const content = await ContentModel.find()
  res.send({ code: 200, msg: '获取成功', content })
})

// 获取搜索内容
router.get('/getSearch', async (req, res) => {
  const search = await SearchModel.find()
  res.send({ code: 200, msg: '获取成功', search })
})

// 添加搜索内容
router.post('/addSearch', (req, res) => {
  SearchModel.create(req.body)
  res.send({ code: 200, msg: '添加成功' })
})

// 删除搜索内容
router.post('/delSearch', async (req, res) => {
  await SearchModel.deleteMany()
  res.send({ code: 200, msg: '删除成功' })
})

// 获取非遗内容
router.get('/getFei', async (req, res) => {
  const fei = await FeiModel.find()
  res.send({ code: 200, msg: '获取成功', fei })
})

// 获取常用人信息
router.get('/getPeople', async (req, res) => {
  const people = await PeopleModel.find()
  res.send({ code: 200, msg: '获取成功', people })
})

// 添加常用人
router.post('/addPeople', (req, res) => {
  PeopleModel.create(req.body)
  res.send({ code: 200, msg: '添加成功' })
})

// 删除常用人
router.post('/delPeople', async (req, res) => {
  const { _id } = req.body
  await PeopleModel.deleteOne({ _id })
  res.send({ code: 200, msg: '删除成功' })
})

//人脸识别验证
router.post('/face', async (req, res) => {
  let b64 = req.body.b64
  const IaiClient = tencentcloud.iai.v20200303.Client;
  try {
    const clientConfig = {
      credential: { secretId: "AKIDsFOK4cx43whIhuAQVNTWM3Y5Zv9A5nHX", secretKey: "HRO7byBetxugGhvzqZAXhdQ00qZBOTLF", },
      region: "ap-beijing",
      profile: { httpProfile: { endpoint: "iai.tencentcloudapi.com", }, },
    };
    const client = new IaiClient(clientConfig);
    const params = {
      "GroupIds": ["WYK123Wyk123"],
      "Image": b64,
      "NeedPersonInfo": 1,
      "QualityControl": 0,
      "FaceMatchThreshold": 85,
    };
    let doc = await client.SearchFaces(params)
    if (doc.Results[0].Candidates.length != 0) {
      res.send({ code: 200, msg: "验证成功！" })
      if (user.length != 0) {
        res.send({ code: 200, msg: "验证成功！", _id: user[0]._id })
      }
    } else {
      res.send({ code: 401, msg: '验证失败！' })
      return false
    }
  } catch (err) { console.log(err); }
})


//米焕增
//订单分类表
router.get('/order_Cate', async function (req, res, next) {
  let data = await order_CateModel.find()
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});
//订单主表
router.get('/order_List', async function (req, res, next) {
  let { ordId } = req.query
  console.log(ordId);
  let lists = [{}]
  if (ordId) {
    lists.push({ ordId: ordId })
  }
  let data = await order_ListModel.find({ $and: lists }).populate('ordId')
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});
//主表详情
router.get('/xiang/:id', async (req, res) => {
  let { id } = req.params
  console.log(id);
  let xia = await order_ListModel.findById(id)
  res.send({
    data: xia
  })
})

//邢馨月
//获取店铺数据
router.get('/getshop', async (req, res) => {
  let shop = await shopModel.find()
  res.send({
    code: 200,
    data: shop
  })
})
//获取店铺的商品数据
router.get('/getshopcommodity', async (req, res) => {
  const shoid = req.query._id
  const data = await commodityModel.find({ shopid: shoid })
  res.send({
    code: 200,
    data: data
  })
})
//地址分类表
router.get('/address_Cate', async function (req, res, next) {
  let data = await addressCateModel.find()
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});

//地址主表
router.get('/address_List', async function (req, res, next) {

  let data = await addressModel.find().populate('adId')
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});
//地址添加
router.post('/address_Add', async function (req, res, next) {
  let data = req.body
  await addressModel.create(data)
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
  })
});

//我的关注分类表
router.get('/guanzhu_Cate', async function (req, res, next) {
  let data = await guanZhuCateModel.find()
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});
//我的关注主表
router.get('/guanzhu_List', async function (req, res, next) {
  let { gzId, name } = req.query
  let lists = [{}]
  let names = new RegExp(name)
  if (gzId) {
    lists.push({ gzId: gzId })
  }
  if (name) {
    lists.push({ name: names })
  }
  let data = await guanZhuModel.find({ $and: lists }).populate('gzId')
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});

//我的动态分类表
router.get('/guandong_Cate', async function (req, res, next) {
  let data = await guanDongCateModel.find()
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});
//我的动态主表
router.get('/guandong_List', async function (req, res, next) {
  let { gdId } = req.query
  let lists = [{}]
  if (gdId) {
    lists.push({ gdId: gdId })
  }

  let data = await guanDongModel.find({ $and: lists }).populate('gdId')
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});

//我的分类
router.get('/yuyue_Cate', async function (req, res, next) {
  let data = await yuYueCateModel.find()
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});
//我的动态主表
router.get('/yuyue_List', async function (req, res, next) {
  let { yyId } = req.query
  let lists = [{}]
  if (yyId) {
    lists.push({ yyId: yyId })
  }

  let data = await yuYueModel.find({ $and: lists }).populate('yyId')
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});

//主表详情
router.get('/yuyue_xiang/:id', async (req, res) => {
  let { id } = req.params
  console.log(id);
  let xia = await yuYueModel.findById(id)
  res.send({
    data: xia
  })
})

//猜灯谜主表
router.get('/Cai_List', async function (req, res, next) {
  let data = await caiListModel.find().populate('caId')
  // console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});

//猜灯谜分类表
router.get('/Cai_Cate', async function (req, res, next) {
  let data = await caiCateModel.find()
  console.log(data);
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
});

//获取店铺数据
router.get('/getshop', async (req, res) => {
  let shop = await shopModel.find()
  res.send({
    code: 200,
    data: shop
  })
})
//获取商品数据
router.get('/getcommodity', async (req, res) => {
  let commodity = await commodityModel.find().populate('shopid')
  res.send({
    code: 200,
    data: commodity
  })
})
//获取关注店铺数据
router.get('/getconcernShop', async (req, res) => {
  let concernShop = await concernShopModel.find().populate('shopid')
  res.send({
    code: 200,
    data: concernShop
  })
})
//获取购物车数据
router.get('/getShoppingCart', async (req, res) => {
  let ShoppingCart = await ShoppingCartModel.find().populate('commodity.commodityid')
  res.send({
    code: 200,
    data: ShoppingCart
  })
})
//
//话题添加
router.post('/addtopic', async (req, res) => {
  HuatiModel.create(req.body)
  res.send({
    code: 200,
    msg: '话题添加成功'
  })
})

//社区列表添加
router.post('/addshequ', (req, res) => {
  ShequModel.create(req.body)
  res.send({
    code: 200,
    msg: '社区添加成功'
  })
})

//帖子添加
router.post('/addtiezi', (req, res) => {
  TieziModel.create(req.body)
  res.send({
    code: 200,
    msg: '帖子添加成功'
  })
})

//社区列表
router.get('/getshequ', async (req, res) => {
  let shequ = await ShequModel.find()
  res.send({
    code: 200,
    data: shequ,
    msg: '社区获取成功'
  })
})

//帖子列表
router.get('/gettiezi', async (req, res) => {
  let tiezi = await TieziModel.find()
  res.send({
    code: 200,
    data: tiezi,
    msg: '帖子获取成功'
  })
})

//话题列表
router.get('/gethuati', async (req, res) => {
  let huati = await HuatiModel.find()
  res.send({
    code: 200,
    data: huati,
    msg: '话题获取成功'
  })
})

//查找帖子
router.get('/findtiezi', async (req, res) => {
  let { _id } = req.query
  // console.log(_id);
  let tiezi = await TieziModel.find({ huatiId: _id })
  res.send({
    code: 200,
    data: tiezi,
    msg: '帖子查找成功'
  })
})
router.get('/findtiezi2', async (req, res) => {
  let { _id } = req.query
  // console.log(_id);
  let tiezi = await TieziModel.find({ _id })
  res.send({
    code: 200,
    data: tiezi,
    msg: '帖子查找成功'
  })
})

//查找话题
router.get('/findhuati', async (req, res) => {
  let { _id } = req.query
  // console.log(_id);

  let huati = await HuatiModel.find({ _id })
  res.send({
    code: 200,
    data: huati,
    msg: '话题查找成功'
  })
})

//修改帖子的状态
router.post('/updatetiezi', async (req, res) => {
  let { _id } = req.body
  let data = await TieziModel.find({ _id })
  //  console.log(data);

  if (data[0].status == true) {
    await TieziModel.updateOne({ _id }, { $set: { status: false } })
    res.send({
      code: 201,
      msg: '帖子状态修改成功'
    })
  } else {
    await TieziModel.updateOne({ _id }, { $set: { status: true } })
    res.send({
      code: 200,
      msg: '帖子状态修改成功'
    })
  }
})

//添加评论消息
router.post('/addpinglun', async (req, res) => {
  pinglunContentModel.create(req.body)
  res.send({
    code: 200,
    msg: '评论添加成功'
  })
})

router.get('/getpinglun', async (req, res) => {
  try {
    // 从数据库中查询所有评论数据，并转换为普通 JavaScript 对象
    let data = await pinglunContentModel.find().lean();

    // 创建一个对象，用于快速查找评论
    let json = {};
    data.forEach(item => {
      json[item['_id']] = item;
    });

    // 存储顶级评论的数组
    let arr = [];

    data.forEach(item => {
      if (!item.pid) {
        // 如果评论没有父评论 ID，则为顶级评论，添加到顶级评论数组中
        arr.push(item);
      } else {
        // 查找父评论
        const parentComment = json[item.pid];
        if (parentComment) {
          if (!parentComment.children) {
            // 如果父评论没有 children 属性，则初始化它
            parentComment.children = [];
          }
          // 将当前评论添加到父评论的 children 数组中
          parentComment.children.push(item);
        }
      }
    });

    // 递归函数，用于将评论数据转换为无限极形式
    function buildTree(comments) {
      return comments.map(comment => {
        if (comment.children && comment.children.length > 0) {
          comment.children = buildTree(comment.children);
        }
        return comment;
      });
    }

    // 调用递归函数处理顶级评论数组
    let treeData = buildTree(arr);

    // 返回响应给客户端
    res.send({
      code: 200,
      data: treeData,
      msg: '评论获取成功'
    });
  } catch (error) {
    // 处理可能出现的错误
    console.error('获取评论数据时出错:', error);
    res.status(500).send({
      code: 500,
      data: null,
      msg: '获取评论数据时出错'
    });
  }
});

router.get('/getpinglun2', async (req, res) => {
  let { _id } = req.query

  try {
    // 从数据库中查询所有评论数据，并转换为普通 JavaScript 对象
    let data = await pinglunContentModel.find({ tieziId: _id }).lean();

    // 创建一个对象，用于快速查找评论
    let json = {};
    data.forEach(item => {
      json[item['_id']] = item;
    });

    // 存储顶级评论的数组
    let arr = [];

    data.forEach(item => {
      if (!item.pid) {
        // 如果评论没有父评论 ID，则为顶级评论，添加到顶级评论数组中
        arr.push(item);
      } else {
        // 查找父评论
        const parentComment = json[item.pid];
        if (parentComment) {
          if (!parentComment.children) {
            // 如果父评论没有 children 属性，则初始化它
            parentComment.children = [];
          }
          // 将当前评论添加到父评论的 children 数组中
          parentComment.children.push(item);
        }
      }
    });

    // 递归函数，用于将评论数据转换为无限极形式
    function buildTree(comments) {
      return comments.map(comment => {
        if (comment.children && comment.children.length > 0) {
          comment.children = buildTree(comment.children);
        }
        return comment;
      });
    }

    // 调用递归函数处理顶级评论数组
    let treeData = buildTree(arr);

    // 返回响应给客户端
    res.send({
      code: 200,
      data: treeData,
      msg: '评论获取成功'
    });
  } catch (error) {
    // 处理可能出现的错误
    console.error('获取评论数据时出错:', error);
    res.status(500).send({
      code: 500,
      data: null,
      msg: '获取评论数据时出错'
    });
  }
});

router.get('/getevent', async (req, res) => {
  let data = await eventModel.find();
  res.send({
    code: 200,
    data: data,
  })
})
const coustpmerserver = require('./coustpmerserver')
router.post('/chart', async (req, res) => {
  let data = req.body.text;
  const result = await coustpmerserver(data)
  res.send({
    code: 200,
    data: result,
  })
})
module.exports = router;
